package com.iot.web.controller.device;

import com.alibaba.fastjson.JSONObject;
import com.iot.common.annotation.Log;
import com.iot.common.core.controller.BaseController;
import com.iot.common.core.domain.AjaxResult;
import com.iot.common.core.domain.entity.SysUser;
import com.iot.common.enums.BusinessType;
import com.iot.common.utils.DateUtils;
import com.iot.common.utils.SecurityUtils;
import com.iot.common.utils.TimeHelper;
import com.iot.common.utils.poi.ExcelUtil;
import com.iot.device.domain.*;
import com.iot.device.dto.GasClientDataStatistics;
import com.iot.device.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *
 * @author iot
 * @date 2023-04-14
 */
@RestController
@RequestMapping("/visual/statisticsPressureSensor")
public class StatisticsPressureSensorController extends BaseController
{

    @Autowired
    public IPressureSensorClientService pressureSensorClientService;
    @Autowired
    public IPressureSensorEventService pressureSensorEventService;
    @Autowired
    public IStatisticsService statisticsService;


    /**
     * 查询设备统计
     */
    @GetMapping("/deviceStat")
    public AjaxResult deviceStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Map<String, Long> clientStatistics = pressureSensorClientService.selectPressureSensorClientStatistics(sysUser.isAdmin() ? null : sysUser.getUserId());
        JSONObject obj = new JSONObject();
        obj.put("totalCount", clientStatistics.getOrDefault("totalCount", 0L));
        obj.put("totalOnlineCount", clientStatistics.getOrDefault("onlineCount", 0L));
        return AjaxResult.success(obj);
    }

    /**
     * 首页查询报警数据
     */
    @GetMapping("/statisticsTotalEvent")
    public AjaxResult statisticsTotalEvent()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalPressureSensorEvent(null, DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalPressureSensorEvent(sysUser.getUserId(), DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
    }
    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/dataVisual")
    public AjaxResult dataVisual()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        PressureSensorClient queryPressureSensorClient = new PressureSensorClient();
        if(!sysUser.isAdmin()){
            queryPressureSensorClient.setUserId(sysUser.getUserId());
        }
        Date now = DateUtils.getNowDate();
        List<PressureSensorClient> pressureSensorClientList = pressureSensorClientService.selectPressureSensorClientList(queryPressureSensorClient);
        TimeHelper.start("pressureSensorEventService.selectRecentPressureSensorEventList");
        List<PressureSensorEvent> pressureSensorEventList = pressureSensorEventService.selectRecentPressureSensorEventList(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        System.out.println("pressureSensorEventService.selectRecentPressureSensorEventList执行耗时：" + TimeHelper.end("pressureSensorEventService.selectRecentPressureSensorEventList"));
        TimeHelper.start("statisticsService.selectPressureSensorEventThisYearStatistics");
        Map<String, Object> pressureSensorEventThisYearStatistics = statisticsService.selectPressureSensorEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        System.out.println("statisticsService.selectPressureSensorEventThisYearStatistics执行耗时：" + TimeHelper.end("statisticsService.selectPressureSensorEventThisYearStatistics"));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        pressureSensorEventThisYearStatistics.put("thisMonth", thisMonth);
        pressureSensorEventThisYearStatistics.put("lastMonth", lastMonth);
        JSONObject data = new JSONObject();
        data.put("pressureSensorClientList", pressureSensorClientList);
        data.put("pressureSensorEventList", pressureSensorEventList);
        data.put("pressureSensorEventThisYearStatistics", pressureSensorEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/visualStatistics")
    public AjaxResult visualStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Long> countPressureSensorClient = pressureSensorClientService.countPressureSensorClientsByUserId(sysUser.isAdmin() ? null : sysUser.getUserId());
        List<Map<String, Long>> eventRank = pressureSensorEventService.selectPressureSensorEventRankByClient(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        Map<String, Object> pressureSensorEventThisYearStatistics = statisticsService.selectPressureSensorEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        JSONObject data = new JSONObject();
        data.put("countPressureSensorClient", countPressureSensorClient);
        data.put("eventRank", eventRank);
        data.put("pressureSensorEventThisYearStatistics", pressureSensorEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     *
     */
    @GetMapping("/eventThisYearStatistics")
    public AjaxResult eventThisYearStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Object> pressureSensorEventThisYearStatistics = statisticsService.selectPressureSensorEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        pressureSensorEventThisYearStatistics.put("thisMonth", thisMonth);
        pressureSensorEventThisYearStatistics.put("lastMonth", lastMonth);
        return AjaxResult.success(pressureSensorEventThisYearStatistics);
    }



    /**
     * 环境监测报警近30日数据趋势
     */
    @GetMapping("/thirtyDaysEventTrend")
    public AjaxResult thirtyDaysEventTrend()
    {
        Date now = DateUtils.getNowDate();
        // 近三十天事件
        Date startTime = DateUtils.getTimesmorning(DateUtils.addDays(now, -31));
        Date endTime = DateUtils.getTimesnight(DateUtils.addDays(now, -1));
        SysUser sysUser = SecurityUtils.getSysUser();
        TimeHelper.start("statisticsService.selectPressureSensorEventTrendStatisticsByDuration");
        List<Map<String, Object>> thirtyDaysChangeList = statisticsService.selectPressureSensorEventTrendStatisticsByDuration(startTime, endTime, sysUser.isAdmin() ? null : sysUser.getUserId());
        System.out.println("statisticsService.selectPressureSensorEventTrendStatisticsByDuration执行耗时：" + TimeHelper.end("statisticsService.selectPressureSensorEventTrendStatisticsByDuration"));
        TreeMap<String, Map<String, Long>> thirtyDaysChange = new TreeMap(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
//                System.out.println(o1 + "    " + o2);
                return DateUtils.parseDate(o1).compareTo(DateUtils.parseDate(o2));
            }
        });
        List<String> days = DateUtils.getDayListOfDate(startTime, endTime);
        for(String day : days){
            thirtyDaysChange.put(day, null);
        }
        for(Map<String, Object> map : thirtyDaysChangeList){
            String date = map.get("eventDate").toString();
            Long LimitAlarmLl = Long.parseLong(map.get("LimitAlarmLl").toString());
            Long L_LimitAlarm = Long.parseLong(map.get("L_LimitAlarm").toString());
            Long LimitAlarmH = Long.parseLong(map.get("LimitAlarmH").toString());
            Long LimitAlarmHh = Long.parseLong(map.get("LimitAlarmHh").toString());
            Map<String, Long> m = new HashMap();
            m.put("LimitAlarmLl", LimitAlarmLl);
            m.put("L_LimitAlarm", L_LimitAlarm);
            m.put("LimitAlarmH", LimitAlarmH);
            m.put("LimitAlarmHh", LimitAlarmHh);
            m.put("total", LimitAlarmLl + L_LimitAlarm + LimitAlarmH + LimitAlarmHh);
            System.out.println(date);
            thirtyDaysChange.put(date, m);
        }
        JSONObject data = new JSONObject();
        data.put("days", days);
        List<Long> LimitAlarmLlList = new ArrayList<>();
        List<Long> L_LimitAlarmList = new ArrayList<>();
        List<Long> LimitAlarmHList = new ArrayList<>();
        List<Long> LimitAlarmHhList = new ArrayList<>();
        List<Long> totalList = new ArrayList<>();
        for(String day : days){
            Map<String, Long> dayData = thirtyDaysChange.get(day);
            LimitAlarmLlList.add(dayData == null ? 0L : dayData.get("LimitAlarmLl"));
            L_LimitAlarmList.add(dayData == null ? 0L : dayData.get("L_LimitAlarm"));
            LimitAlarmHList.add(dayData == null ? 0L : dayData.get("LimitAlarmH"));
            LimitAlarmHhList.add(dayData == null ? 0L : dayData.get("LimitAlarmHh"));
            totalList.add(dayData == null ? 0L : dayData.get("total"));
        }
        data.put("LimitAlarmLlList", LimitAlarmLlList);
        data.put("L_LimitAlarmList", L_LimitAlarmList);
        data.put("LimitAlarmHList", LimitAlarmHList);
        data.put("LimitAlarmHhList", LimitAlarmHhList);
        data.put("totalList", totalList);
        return AjaxResult.success(data);
    }


    /**
     * 报警数据分类统计（全部）
     */
    @GetMapping("/eventStat")
    public AjaxResult eventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalPressureSensorEventGroupByType(null));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalPressureSensorEventGroupByType(sysUser.getUserId()));
        }
    }

    /**
     * 报警数据分类统计（本日）
     */
    @GetMapping("/todayEventStat")
    public AjaxResult todayEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTodayPressureSensorEventGroupByType(null, DateUtils.getTimesmorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTodayPressureSensorEventGroupByType(sysUser.getUserId(), DateUtils.getTimesmorning(now)));
        }
    }

    /**
     * 报警数据分类统计（本月）
     */
    @GetMapping("/monthEventStat")
    public AjaxResult monthEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsMonthPressureSensorEventGroupByType(null, DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsMonthPressureSensorEventGroupByType(sysUser.getUserId(), DateUtils.getTimesMonthStartMorning(now)));
        }
    }
}
